package com.zhx.sweet.authentication.encrypt;

import com.zhx.sweet.common.constants.SecurityConstants;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * encrpt 加密登录的拦截器  采用对称加密
 * @author zhanghaixuan
 * @create 2018年06月30日15:40:18
 **/
public class EncryptAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private String encrptParamter = SecurityConstants.DEFAULT_PARAMETER_ENCRYPTLOGIN;
    private boolean postOnly = true;

    public EncryptAuthenticationFilter() {
        super(new AntPathRequestMatcher(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_ENCRYPT,"POST"));
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException{
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String encrypt = obtainEncrypt(request);

        if (encrypt == null) {
            encrypt = "";
        }

        encrypt = encrypt.trim();

        EncryptAuthenticationToken encryptAuthenticationToken=new EncryptAuthenticationToken(encrypt);

        // Allow subclasses to set the "details" property
        setDetails(request, encryptAuthenticationToken);

        return this.getAuthenticationManager().authenticate(encryptAuthenticationToken);
    }

    protected String obtainEncrypt(HttpServletRequest request) {
        return request.getParameter(encrptParamter);
    }

    protected void setDetails(HttpServletRequest request,
                              EncryptAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }


    public String getEncrptParamter() {
        return encrptParamter;
    }

    public void setEncrptParamter(String encrptParamter) {
        Assert.hasText(encrptParamter, "encrpt parameter must not be empty or null");
        this.encrptParamter = encrptParamter;
    }

    public boolean isPostOnly() {
        return postOnly;
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }
}
